<template>
  <el-card class="box-card">
    <el-row>
      <!-- 左侧树形图 -->
      <el-col :span="3" class="box-left">
        <el-tree
          :data="treedata"
          @node-click="handleCheckChange"
          node-key="deptId"
          :props="deptTreeProps"
          ref="tree"
          highlight-current
          default-expand-all
        ></el-tree>
      </el-col>
      <!-- 左侧树形图 -->
      <!-- 右侧表格 -->
      <el-col :span="21">
        <div class="header">
          <el-input
            v-model="listQuery.username"
            placeholder="用户名"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-select
            v-model="listQuery.status"
            placeholder="用户状态"
            clearable
            style="width: 150px"
            class="filter-item"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >搜索
          </el-button>
          <el-button
            v-waves
            :loading="downloadLoading"
            class="filter-item"
            type="primary"
            icon="el-icon-download"
            @click="handleDownload"
          >导出
          </el-button>
          <el-button
            v-waves
            class="filter-item"
            type="success"
            icon="el-icon-plus"
            @click="showCreateDialog"
          >新增用户
          </el-button>
        </div>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80px">
            <template slot-scope="scope">
              <span>{{ scope.row.uid }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账号" min-width="100px" align="center">
            <template slot-scope="{row}">
              <span class="link-type" @click="handleUpdate(row)">{{ row.username }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="姓名" min-width="100px" align="center">
            <template slot-scope="{row}">
              <span class="link-type">{{ row.realName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="真实姓名" width="120px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.realName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="center" width="150px">
            <template slot-scope="scope">
              <el-tag type="default">{{ scope.row.deptName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="职位" align="center" width="150px">
            <template slot-scope="{row}">
              <el-tag type="default">{{ row.postName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="角色" align="center" width="150px">
            <template slot-scope="{row}">
              <el-tag type="default">{{ row.roleName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="280px"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="{row}">
              <el-button
                type="success"
                icon="el-icon-view"
                size="mini"
                @click="showViewDialog(row.uid)"
                plain
              >查看
              </el-button>
              <el-button type="primary" size="mini" @click="showUpdateDialog(row.uid)" icon="el-icon-edit">编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="deleteHandle(row.uid)"
                icon="el-icon-delete"
                plain
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
          :title="titleMap[dialogStatus]"
          :lock-scroll="true"
          :visible.sync="dialogFormVisible"
          :before-close="handleClose"
        >
          <div class="dialogBody">
            <el-scrollbar wrap-class="scrollbar-wrapper">
              <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="80px"
                :disabled="!(dialogStatus ==='update' || dialogStatus ==='create')"
              >
                <el-row>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="登陆名" prop="username">
                      <el-input v-model="form.username" placeholder="请输入登陆名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="真实姓名" prop="realName">
                      <el-input v-model="form.realName" placeholder="请输入真实姓名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :xs="24"
                    :md="12"
                    v-if="(dialogStatus ==='update' || dialogStatus ==='create')"
                  >
                    <el-form-item label="密码" prop="password">
                      <el-input v-model="form.password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :xs="24"
                    :md="12"
                    v-if="(dialogStatus ==='update' || dialogStatus ==='create')"
                  >
                    <el-form-item label="确认密码" prop="rePassword">
                      <el-input v-model="form.rePassword" placeholder="请重新输入密码"></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- 基本信息  end -->
                  <p class="ptitle">相关信息</p>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="部门" prop="selectedDeptIds">
                      <el-cascader
                        v-model="form.selectedDeptIds"
                        :options="deptIdOptions"
                        :props="deptProps"
                        :show-all-levels="false"
                        collapse-tags
                        clearable></el-cascader>
                      <!-- 选择部门 -->
                    </el-form-item>
                  </el-col>
                  <!-- 职位 -->
                  <el-col :xs="24" :md="12">
                    <el-form-item label="职位" prop="selectedPostIds">
                      <el-select
                        v-model="form.selectedPostIds"
                        multiple
                        collapse-tags
                        placeholder="请选择">
                        <el-option
                          v-for="posi in posiOptions"
                          :key="posi.id"
                          :label="posi.postName"
                          :value="posi.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <!-- 职位 -->
                  <el-col :xs="24" :md="12">
                    <el-form-item label="角色" prop="selectedRoleIds">
                      <el-cascader
                        v-model="form.selectedRoleIds"
                        :options="roleOptions"
                        :props="roleProps"
                        :show-all-levels="false"
                        collapse-tags
                        clearable></el-cascader>
                      <!-- 选择角色 -->
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="状态" prop="status" style="width:100%">
                      <el-select
                        v-model="form.status"
                        placeholder="用户状态"
                        clearable
                        style="width: 150px"
                        class="filter-item"
                      >
                        <el-option
                          v-for="item in statusOptions"
                          :key="item.key"
                          :label="item.value"
                          :value="item.key"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :xs="24"
                    :md="12"
                    v-if="!(dialogStatus ==='update' || dialogStatus ==='create')"
                  >
                    <el-form-item label="创建时间" prop="createTime">
                      <el-input v-model="form.createTime" placeholder="请输入创建时间"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :xs="24"
                    :md="24"
                    v-if="!(dialogStatus ==='update' || dialogStatus ==='create')"
                  >
                    <el-form-item label="创建IP" prop="createIp">
                      <el-input v-model="form.createIp" placeholder="请输入创建ip"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :xs="24"
                    :md="24"
                    v-if="!(dialogStatus ==='update' || dialogStatus ==='create')"
                  >
                    <el-form-item label="最后登陆" prop="lastLoginTime">
                      <el-input v-model="form.lastLoginTime" placeholder="请输入最后一次登陆时间"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :xs="24"
                    :md="24"
                    v-if="!(dialogStatus ==='update' || dialogStatus ==='create')"
                  >
                    <el-form-item label="登陆IP" prop="lastLoginIp">
                      <el-input v-model="form.lastLoginIp" placeholder="请输入最后一次登陆ip"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :xs="24"
                    :md="24"
                    v-if="!(dialogStatus ==='update' || dialogStatus ==='create')"
                  >
                    <el-form-item label="登录次数" prop="loginNum">
                      <el-input v-model="form.loginNum" placeholder="请输入登录次数"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-scrollbar>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              v-if="(dialogStatus ==='update' || dialogStatus ==='create')"
              @click="saveHandle"
            >保存
            </el-button>
          </div>
        </el-dialog>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.current"
          :limit.sync="listQuery.size"
          @pagination="getList"
        />
      </el-col>
      <!-- 右侧表格 -->
    </el-row>
  </el-card>
</template>
<script>
import {page, findById, save, deleteById, updateById} from "@/api/user";
import {list, tree} from "@/api/dept"; // 引用部门树形api接口
import {roleTree} from "@/api/role"; // 引用角色树形api接口
import {getPositionList} from "@/api/position"; // 引用职位列表api接口
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {error} from "util";

const statusOptions = [
  {key: 1, value: "正常"},
  {key: 0, value: "禁用"},
  {key: -1, value: "删除"},
];

export default {
  name: "SysUser",
  components: {Pagination},
  directives: {waves},

  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.form.rePassword !== "") {
          this.$refs.form.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 部门选择
      deptTreeProps: {
        label: "deptName",
        children: "children",
      },
      currentNodekey: [], //默认选中的节点树
      expandedkeys: [], //默认展开的节点树
      deptProps: {
        multiple: false,
        checkStrictly: true,
        label: 'deptName',
        children: "children",
        value: "deptId",
      },
      // 部门选择
      // 角色选择
      roleProps: {
        multiple: false,
        checkStrictly: true,
        label: 'roleName',
        children: "children",
        value: "roleId",
      },
      // 角色选择
      posiOptions: [],
      roleOptions: [],
      deptIdOptions: [],

      // 职位下拉
      imageUrl: '',
      mineStatusValue: [],
      treedata: [],
      // userType: '',
      statusOptions,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        username: undefined,
        userType: undefined,
        deptId: undefined,
        descs: undefined,
        ascs: undefined,
        realName: undefined,
      },
      rules: {
        realName: [{required: true, trigger: "blur", message: "真实姓名不能为空"}],
        email: [{required: true, trigger: "blur", message: "邮箱不能为空"}],
        phone: [{required: true, trigger: "blur", message: "手机号不能为空"}],
        username: [
          {required: true, trigger: "blur", message: "登陆名不能为空"},
        ],
        password: [{validator: validatePass, trigger: "blur"}],
        rePassword: [{validator: validatePass2, trigger: "blur"}],
        selectedDeptIds: [
          {
            required: true,
            trigger: "blur",
            message: "部门不能为空",
          },
        ],
        selectedRoleIds: [
          {
            required: true,
            trigger: "blur",
            message: "角色不能为空",
          },
        ],
        selectedPostIds: [
          {
            required: true,
            trigger: "blur",
            message: "职位不能为空",
          },
        ],
        downloadLoading: false,
        status: [
          {
            required: true,
            trigger: "blur",
            message: "状态不能为空",
          },
        ],
      },
      dialogFormVisible: false,
      downloadLoading: false,
      titleMap: {
        update: "编辑用户",
        create: "新增用户",
        view: "查看用户",
      },
      dialogStatus: "",
      form: {
        email: '',
        realName: '',
      },
    };
  },

  created() {
    this.getList();
    this.gettreeList();
  },
  methods: {

    // 左侧树形图
    handleCheckChange(data) {
      this.listQuery.deptId = data.deptId;
      this.handleFilter();
    },
    gettreeList() {
      let th = this;
      tree().then((respo) => {
        th.treedata = respo.data;
      });
    },
    // 弹框部门树形图
    getDeptIdTree() {
      let th = this;
      tree().then((respo) => {
        th.deptIdOptions = respo.data;
        // console.log(respo.data)
      });
    },
    // 弹框角色树形图
    getRoleTree() {
      let th = this;
      roleTree().then((respo) => {
        th.roleOptions = respo.data;
        // console.log(respo.data)
      });
    },
    // 弹框职位树形图
    getPositionList() {
      let th = this;
      getPositionList().then((respo) => {
        th.posiOptions = respo.data;
        // console.log(respo.data)
      });
    },
    getList() {
      this.listLoading = true;
      page(this.listQuery).then((response) => {
        this.list = response.data.records;
        this.total = response.data.total;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
        // console.log(response.data)
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {
        });
    },
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: "操作Success",
    //     type: "success",
    //   });
    //   row.status = status;
    // },

    sortChange(data) {
      const {prop, order} = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.ascs = "uid";
        this.listQuery.descs = null;
      } else {
        this.listQuery.descs = "uid";
        this.listQuery.ascs = null;
      }
      this.handleFilter();
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.getList();
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["用户id", "用户名", "电子邮箱", "手机号"];
        const filterVal = ["uid", "username", "email", "phone"];
        const data = this.formatJson(filterVal, this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "user-list",
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    submitQuery() {
      this.listQuery.current = 1;
      this.getList();
    },
    clearQuery() {
      this.listQuery.uid = undefined;
      this.submitQuery();
    },
    showCreateDialog() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.form = {};
      this.getRoleTree();
      this.getDeptIdTree();
      this.getPositionList();
    },
    showViewDialog(id) {
      this.resetForm();
      this.dialogStatus = "view";
      this.getRoleTree();
      this.getDeptIdTree();
      this.getPositionList();
      findById(id).then((response) => {
        this.form = response.data;

        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
      this.dialogFormVisible = true;

    },
    showUpdateDialog(id) {
      // this.resetForm();
      this.dialogStatus = "update";
      this.getRoleTree();
      this.getDeptIdTree();
      this.getPositionList();
      findById(id).then((response) => {
        this.form = response.data;

        //  console.log(this.form)
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
      this.dialogFormVisible = true;
    },
    deleteHandle(id) {
      let me = this;
      this.$confirm("是否删除这条数据？?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteById(id).then(() => {
          me.getList();
        });
      });
    },
    saveHandle(form) {
      let me = this;
      me.$refs.form.validate((valid) => {
        if (valid) {
          me.downloadLoading = true;
          console.log(me.form.selectedDeptIds);
          me.form.selectedDeptIdsStr = me.form.selectedDeptIds.join();
          me.form.selectedRoleIdsStr = me.form.selectedRoleIds.join();
          me.form.selectedPostIdsStr = me.form.selectedPostIds.join();

          if (me.dialogStatus === "create") {
            save(this.form).then(() => {
              this.listLoading = false;
              me.dialogFormVisible = false;
              me.getList();
            });
            // console.log(me.dialogStatus)
          } else {
            updateById(this.form).then(() => {
              this.listLoading = false;
              me.dialogFormVisible = false;
              me.getList();
            });
            // console.log(me.dialogStatus)
          }
        } else {
          return false;
        }
      });
    },
    resetForm() {
      if (this.$refs.form !== undefined) {
        this.$refs.form.resetFields();
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  color: #4d95fd;
  font-weight: bold;
}

.el-select-dropdown__item.hover, .el-select-dropdown__item:hover {
  background-color: #fff;
}

.box-left {
  padding-right: 15px;
}

.ptitle {
  color: #999;
  font-size: 14px;
}
.box-card {
  height: 100%;
  margin: 10px 8px;
  padding: 0;
}

.header {
  margin-bottom: 10px;
}

.dialogBody {
  height: 400px;
  overflow: hidden;
}

.scrollbar-wrapper {
  overflow-x: hidden !important;
}

.el-scrollbar__bar.is-vertical {
  right: 0px;
}

.el-scrollbar {
  height: 100%;
}

.user-avatar {
  cursor: pointer;
  width: 40px;
  height: 40px;
  border-radius: 10px;
}
</style>
